package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.*;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestSoulApiImpl implements TestSoulApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询试卷
     * @return
     */
    @Override
    public List<Paper> findPapers() {
        Query query = new Query();
        return mongoTemplate.find(query,Paper.class);
    }

    /**
     * 计算总分
     * @param questionId
     * @param optionId
     * @return
     */
    @Override
    public Integer computeScore(String questionId, String optionId) {

        Query query = new Query(Criteria.where("questionId").is(questionId).and("optionId").is(optionId));
        AnswerList answerLists = mongoTemplate.findOne(query, AnswerList.class);

        return answerLists.getGrade();
    }

    /**
     * 保存report
     * @param report
     * @return
     */
    @Override
    public String saveReport(Report report) {
        //查询report表中是否有此用户和相应等级的report
        Query query = new Query(Criteria.where("userId").is(report.getUserId()).and("type").is(report.getType()));
        Report lastReport = mongoTemplate.findOne(query,Report.class);
        if (lastReport != null){
            mongoTemplate.remove(query,Report.class);
        }

        report.setId(new ObjectId());
        mongoTemplate.save(report);
        return report.getId().toHexString();
    }


    /**
     * 通过主键Id查询report
     * @param reportId
     * @return
     */
    @Override
    public Report findById(String reportId) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(reportId)));
        return mongoTemplate.findOne(query,Report.class);
    }

    /**
     * 通过userId查询report
     * @param userId
     * @return
     */
    @Override
    public List<Report> findByUserId(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.asc("type")));
        List<Report> reports = mongoTemplate.find(query,Report.class);
        return reports;
    }
}
